import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_picker/picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../common/utils/screen_size_utils.dart';
import '../config/common_string_config.dart';
import '../config/pick_name_utils.dart';
import '../config/theme_color.dart';
import '../generated/l10n.dart';
import '../requst/dio_http_utils.dart';

class PicVideoCommonUtils {
  static double imgHeight = 200;
  static double itemHeight = 50;
  static double bottomHeight = 67;
  static double tabHeight = 40;

  //判断时间是否超过10分钟
  static bool isTimeExceeded(int startTime) {
    int currentTime = DateTime.now().millisecondsSinceEpoch;
    double difference = (currentTime - startTime) / (1000 * 60);
    return difference.toInt() > 1;
  }

  static requestOTSToken(String? imgPath,
      {required MethodChannel methodChannel}) async {
    String aKStr = "";
    String sKStr = "";
    String aKTokenStr = "";
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    CommonStringConfig.firstTimeStamp =
        sharedPreferences.getInt('firstTimeStamp') ?? 0;
    if (CommonStringConfig.firstTimeStamp == 0 ||
        isTimeExceeded(CommonStringConfig.firstTimeStamp)) {
      print('超过10分钟了');
      var res = await HttpDioUtils.request('getUploadToken', params: {});
      if (res != null && res['ErrCode'] == 0) {
        Map resMap = res['Resp'];
        aKStr = resMap['Ak'];
        sKStr = resMap['Sk'];
        aKTokenStr = resMap['Token'];
        sharedPreferences
            .setStringList('uploadToken', [aKStr, sKStr, aKTokenStr]);
        CommonStringConfig.uploadAKStr = aKStr;
        CommonStringConfig.uploadSKStr = sKStr;
        CommonStringConfig.uploadToken = aKTokenStr;
        int timeStamp = DateTime.now().millisecondsSinceEpoch;
        CommonStringConfig.firstTimeStamp = timeStamp;
        sharedPreferences.setInt('firstTimeStamp', timeStamp);
      }
    } else {
      print('没有超过10分钟了');
      if (CommonStringConfig.uploadToken.isEmpty) {
        List<String>? resList = sharedPreferences.getStringList('uploadToken');
        if (resList != null) {
          CommonStringConfig.uploadAKStr = resList.first;
          CommonStringConfig.uploadSKStr = resList[1];
          CommonStringConfig.uploadToken = resList.last;
        }
      }

      aKStr = CommonStringConfig.uploadAKStr;
      sKStr = CommonStringConfig.uploadSKStr;
      aKTokenStr = CommonStringConfig.uploadToken;
    }
    String type = isPictrueConetent(imgPath ?? '') ? "png" : 'mp4';
    methodChannel
        .invokeMethod('uploadImg', [imgPath, aKStr, sKStr, aKTokenStr, type]);
  }

//随机数
  static int getRandomNum() {
    Random random = Random();
    int min = 100000000; // 10位数的最小值
    int max = 900000000; // 18位数的最大值
    int randomInt = min + random.nextInt(max - min);
    return randomInt;
  }

  //宽高比
  static Map rateMap() {
    return {
      '16:9': '512x288',
      '9:16': '288x521',
      '1:1': '512x512',
      '4:3': '512x384',
      '3:4': '384x512'
    };
  }

  //宽高比
  static Map widthHeightMap() {
    return {
      '512x288': '16:9',
      '288x521': '9:16',
      '512x512': '1:1',
      '512x384': '4:3',
      '384x512': '3:4'
    };
  }

//宽高比试图
  static getRateBottomView(BuildContext context,
      {required List rateKeyList, required Function tapAction}) {
    return PickNameUtils.showStringPicker(context,
        data: rateKeyList,
        title: '选择比例', clickCallBack: (Picker picker, List<int> selected) {
      tapAction(picker.getSelectedValues().first);
    });
  }

  static Widget getChoseRatioItemView({String leftName = ''}) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          const SizedBox(
            height: 12,
          ),
          Text(
            leftName,
            style: const TextStyle(fontSize: 18),
          ),
          const SizedBox(
            height: 12,
          ),
          Container(
            color: ThemeColor.lineColor,
            height: 0.5,
          ),
        ],
      ),
    );
  }

  static Widget getChoseItemView(
      {String leftName = '',
      String rightName = '',
      Function? tapAction,
      Function? refreshAction,
      bool isHiddenRefresh = false}) {
    return GestureDetector(
      onTap: () {
        if (tapAction != null) {
          tapAction();
        }
      },
      child: Container(
        color: Colors.white,
        child: Column(
          children: [
            const SizedBox(
              height: 12,
            ),
            Row(
              children: [
                const SizedBox(
                  width: 20,
                ),
                SizedBox(
                  width: 140,
                  child: Text(
                    leftName,
                  ),
                ),
                Text(
                  rightName,
                ),
                const SizedBox(
                  width: 40,
                ),
                Offstage(
                  offstage: isHiddenRefresh,
                  child: GestureDetector(
                    onTap: () {
                      if (refreshAction != null) {
                        refreshAction();
                      }
                    },
                    child: Icon(
                      Icons.refresh_rounded,
                      color: ThemeColor.mainColor,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 12,
            ),
            Container(
              color: ThemeColor.lineColor,
              height: 0.5,
            ),
          ],
        ),
      ),
    );
  }

  static Widget getItemView(
      {String leftName = '',
      required TextEditingController textEditingController,
        required FocusNode focusNode,
      String placeStr = ''}) {
    return SizedBox(
      height: itemHeight,
      child: Column(
        children: [
          Row(
            children: [
              const SizedBox(
                width: 20,
              ),
              SizedBox(
                width: 140,
                child: Text(
                  leftName,
                ),
              ),
              Expanded(
                child: TextField(
                  focusNode: focusNode,
                  controller: textEditingController,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                  ),
                  onChanged: (res) {},
                  decoration: InputDecoration(
                    hintText: placeStr,
                    hintStyle: TextStyle(
                        fontSize: 14, color: ThemeColor.textColorSecond),
                    border: InputBorder.none,
                  ),
                ),
              ),
            ],
          ),
          Container(
            color: ThemeColor.lineColor,
            height: 0.5,
          ),
        ],
      ),
    );
  }

  static bool isPictrueConetent(String path) {
    if (path.endsWith('png')) {
      return true;
    }
    if (path.endsWith('jpeg')) {
      return true;
    }
    if (path.endsWith('jpg')) {
      return true;
    }
    if (path.endsWith('webp')) {
      return true;
    }
    if (path.endsWith('svg')) {
      return true;
    }
    if (path.endsWith('gif')) {
      return true;
    }
    if (path.endsWith('gif')) {
      return true;
    }
    return false;
  }

  static Widget deleteViewAndSubmitAction(BuildContext context,
      {required Function delAction, required Function submitAction}) {
    return SizedBox(
      height: 67,
      child: Column(
        children: [
          Container(
            color: ThemeColor.lineColor,
            height: 0.5,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              getBottomViewBtn(name: S.of(context).delete, tapAction: delAction),
              getBottomViewBtn(name: S.of(context).generation, tapAction: submitAction),
            ],
          ),
        ],
      ),
    );
  }

  static getBottomViewBtn({required String name, required Function tapAction}) {
    return TextButton(
        onPressed: () {
          tapAction();
        },
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
          decoration: BoxDecoration(
              color: ThemeColor.mainColor,
              borderRadius: BorderRadius.circular(4)),
          child: Text(
            name,
            style: const TextStyle(
              color: Colors.white,
            ),
          ),
        ));
  }

  static double middleHeight(BuildContext context) {
    return ScreenSizeUtils.deviceScreenHeight(context) -
        imgHeight -
        10 -
        itemHeight * 4 -
        tabHeight -
        ScreenSizeUtils.navigatBarHeight(context) -
        bottomHeight -
        ScreenSizeUtils.statusBarHeight(context) -
        20;
  }
}
